import styled from 'styled-components';
import React, { CSSProperties, FC, useCallback, useEffect, useState } from 'react';
import {
    FooterToolbar,
    PageContainer,
    ProForm,
    ProFormDateRangePicker,
    ProFormDigit,
    ProFormRadio,
    ProFormItem,
    ProFormSelect,
    ProFormText,
    ProFormTextArea,
    ProFormUploadButton,
    ProLayout,
} from '@ant-design/pro-components';

import { QiniuFileUpload } from '@/components';
import { Application, ApplicationCategory, ApplicatonPublicStatus, appstoreApplicationCommit, appstoreCategoriesList2value, appstoreGetCategories, appstoreQueryApplicationById, appstoreSaveApplication } from '@/services';
import { Button, Card, Spin } from 'antd';
import { getNowFormatDate, getUserId } from '@/utils';
import { appUploadProjectApplication, ProjectApplication } from '@/services/local';

export interface ApplicationPublishProps {
    style?: CSSProperties;
    application: ProjectApplication;
}


export const ApplicationPublish: FC<ApplicationPublishProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    const [published, setPublished] = useState<boolean>(false);

    const [categories, setCategories] = useState<Array<ApplicationCategory>>([]);

    const [application, setApplication] = useState<Application | null>(null);

    const [icon, setIcon] = useState<Array<string>>([]);

    const [images, setImages] = useState<Array<string>>([]);

    const refresh = async () => {
        setLoading(true);
        try {
            let categories = await appstoreGetCategories();
            setCategories(categories);
            let app = await appstoreQueryApplicationById(props.application.identifier);
            console.log(app);
            setApplication(app);
        } catch (error) {
            console.error(error);
        }
        setLoading(false);
    };

    useEffect(() => {
        refresh();
    }, []);

    if (loading) {
        return (
            <Container>
                <Spin></Spin>
            </Container>
        );
    }

    //
    if (!application && props.application) {
        //没有找到, 发布界面
        return (
            <Container>
                <Card>
                    <ProForm<Application>
                        request={async () => {
                            return {
                                categories: [],
                                identifier: props.application.identifier,
                                title: props.application.title,
                                name: props.application.name,
                                icon: props.application.icon,
                                version: 'V1.0.0',
                                applicationType: props.application.application_type,
                                description: props.application.description,
                                images: [],
                                options: ''
                            };
                        }}
                        onFinish={async (values) => {
                            //TODO 校验
                            console.log(values);
                            try {
                                let url = await appUploadProjectApplication(props.application);
                                //
                                let application = {
                                    user_id: getUserId(),
                                    categories: appstoreCategoriesList2value(values.categories as string[]),
                                    identifier: props.application.identifier,
                                    name: values.name,
                                    icon: icon && icon.length > 0 ? icon[0] : '',
                                    version: values.version,
                                    application_type: props.application.application_type ? props.application.application_type : 'VIEWER',
                                    download: url,
                                    images: images.map((item) => item),
                                    options: values.options ? values.options : '',
                                    description: values.description,
                                };
                                console.log(application);
                                //
                                let res = await appstoreSaveApplication(application);
                                //添加完成之后，提交审核
                                res = await appstoreApplicationCommit(props.application.identifier);
                            } catch (err) {
                                console.error(err);
                            }
                            await refresh();
                        }}
                        submitter={false}
                    >
                        <ProForm.Group>
                            <ProFormSelect
                                rules={[{ required: true }]}
                                options={categories ? categories.map((item, index) => {
                                    return {
                                        value: item.code + '',
                                        label: item.name,
                                    }
                                }) : []}
                                fieldProps={{ mode: "multiple", maxCount: 3 }}
                                width="sm"
                                name="categories"
                                tooltip="应用的相关分类，用于应用商店筛选"
                                label="分类"
                            />
                            <ProFormText width="sm" fieldProps={{}}
                                tooltip="应用显示的名称"
                                rules={[{ required: true }]} name="name" label="名称" />
                            <ProFormText width="sm" fieldProps={{}}
                                tooltip="例如:V1.2.3"
                                rules={[{ required: true }]} name="version" label="版本" />
                        </ProForm.Group>

                        <ProFormItem
                            extra="只能上传jpg/png文件,且不大于1MB"
                            rules={[{ required: true }]}
                            label="图标"
                            name="icon">
                            <QiniuFileUpload
                                title={'上传图标'}
                                listType={'picture-card'}
                                accept={"image/png, image/jpeg"}
                                max={1}
                                isPicture={true}
                                filePath={`g01/applications/images/${getNowFormatDate('')}`}
                                onChange={async (files) => {
                                    setIcon(files);
                                }}></QiniuFileUpload>
                        </ProFormItem>

                        <ProFormTextArea
                            rules={[{ required: true }]} width="xl" fieldProps={{ rows: 4 }} label="描述" name="description" />


                        <ProFormItem
                            extra="只能上传jpg/png文件,且不大于1MB"
                            rules={[{ required: true }]}
                            label="应用效果图片"
                            name="images">
                            <QiniuFileUpload
                                title={'上传效果图片'}
                                listType={'picture-card'}
                                accept={"image/png, image/jpeg"}
                                max={3}
                                isPicture={true}
                                filePath={`g01/applications/images/${getNowFormatDate('')}`}
                                onChange={async (files) => {
                                    setImages(files);
                                }}></QiniuFileUpload>
                        </ProFormItem>
                        <ProFormItem>
                            <Button type="primary" htmlType="submit">
                                上传应用
                            </Button>
                        </ProFormItem>
                    </ProForm>
                </Card>

            </Container>
        );
    }

    if (application && application.public_status === ApplicatonPublicStatus.PUBLIC) {
        //审核成功
        return (
            <Container>
                <Button>取消发布</Button>
                <Button>更新版本</Button>
            </Container>
        );
    }
    if (application && application.public_status === ApplicatonPublicStatus.AUDITING) {
        //审核中
        return (
            <Container>
                审核中
            </Container>
        );
    }
    return (
        <Container>
            {application.identifier}
        </Container>
    );
}

const Container = styled.div`
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
`;


export default {}